/**
 * Simple event bus implementation for Vue 3
 * Allows components to communicate without direct parent-child relationship
 */
class EventBus {
  private events: Map<string, Set<Function>>

  constructor() {
    this.events = new Map()
  }

  /**
   * Subscribe to an event
   * @param event Event name
   * @param callback Callback function to be called when event is emitted
   * @returns Unsubscribe function
   */
  on(event: string, callback: Function): () => void {
    if (!this.events.has(event)) {
      this.events.set(event, new Set())
    }
    
    this.events.get(event)!.add(callback)
    
    // Return unsubscribe function
    return () => {
      this.events.get(event)?.delete(callback)
      if (this.events.get(event)?.size === 0) {
        this.events.delete(event)
      }
    }
  }

  /**
   * Emit an event with data
   * @param event Event name
   * @param data Data to be passed to callbacks
   */
  emit(event: string, data?: any): void {
    if (this.events.has(event)) {
      this.events.get(event)!.forEach(callback => {
        callback(data)
      })
    }
  }

  /**
   * Remove all listeners for an event
   * @param event Event name
   */
  off(event: string): void {
    this.events.delete(event)
  }

  /**
   * Clear all events and listeners
   */
  clear(): void {
    this.events.clear()
  }
}

// Create a singleton instance
const bus = new EventBus()

export default bus
